<!--
map-factory使用示例
@author pan
@date 2021/11/27
-->
<script lang="ts" setup>
import { ref } from 'vue'
import createMapper from 'map-factory'

const backendData1 = {
  name: '张三',
  age: 14,
  male: true,
  hobby: ['足球', '篮球'],
  birthday: new Date(),
  father: {
    name: '李四',
  },
  books: [{ title: '我是谁' }, { title: '不是钢铁巨人' }],
}
const frontendData1 = ref()
function onConvert1() {
  const mapper = createMapper()
  mapper.map('name').to('realName')
  frontendData1.value = mapper.execute(backendData1)
}
function onConvert2() {
  const mapper = createMapper()
  mapper
    .map('name')
    .to('realName')
    .map('age')
    .to('age')
    .map('hobby[0]')
    .to('firstHobby')
  frontendData1.value = mapper.execute(backendData1)
}
function onConvert3() {
  const mapper = createMapper()
  mapper
    .map('name')
    .to('realName')
    .map('age')
    .to('age')
    .map('hobby[0]')
    .to('firstHobby')
    .map('father.name')
    .to('fatherName')
    .map('father')
    .to('father')
  frontendData1.value = mapper.execute(backendData1)
}

function onConvert4() {
  const mapper = createMapper()
  mapper
    .map('name')
    .to('realName')
    .map('age')
    .to('age')
    .map('hobby[0]')
    .to('firstHobby')
    .map('father.name')
    .to('fatherName')
    .map('father')
    .to('father')
    .map('books[1]')
    .to('likeBook')
    .map('books[1].title')
    .to('likeBookTitle')
  frontendData1.value = mapper.execute(backendData1)
}
</script>

<template>
  <div>
    map-factory使用示例[该工具用于前后端数据结构不一致时的对象数据结构转换]
  </div>
  <p>
    <router-link :to="{ name: 'Home' }">返回</router-link>
  </p>
  <div>后端数据结构1</div>
  <p>{{ backendData1 }}</p>
  <div><button @click="onConvert1">复制某个属性，并换名</button></div>
  <div>
    <button @click="onConvert2">
      复制数组中某个元素，作为另一个对象的属性
    </button>
  </div>
  <div><button @click="onConvert3">子对象属性复制</button></div>
  <div><button @click="onConvert4">数组对象复制</button></div>
  <p>{{ frontendData1 }}</p>
  <p>
    <router-link :to="{ name: 'Home' }">返回</router-link>
  </p>
</template>

<style lang="scss" scoped></style>
